package com.gable.report.util;


import com.gable.report.model.ChartsCityWeatherView;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.*;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: 杨青桦
 * @Description:  调用hospital项目接口工具类
 * @Date: 2017/11/28 15:33
 */
public class HttpProcessUtil {

    private static final Log logger = LogFactory.getLog(HttpProcessUtil.class);

    public static  List<Header> headerList = Arrays.asList(new Header("report", "auth")); //头信息用于权限验证

    private static final String url = "http://flash.weather.com.cn/wmaps/xml/";


    /**
     * @Author: 杨青桦
     * @Description:  从配置文件中读取医院项目地址，并组装url(报表和医院项目不在同一服务器也能使用)
     * @Date: 2018/3/21 15:32
     * @param address
     * @param url
     * @return
     */
    public static String getAccessPath(String address,String url){
        return address + url;
    }


    /**
     * @Author: 杨青桦
     * @Description: 获取天气接口返回的xml字符串
     * @Date: 2018/1/23 14:13
     * @param address
     * @return
     */
    public static String getXml(String address) {

        HttpClient httpClient = new HttpClient();
        // 创建GET方法的实例
        GetMethod getMethod = new GetMethod(url + address +".xml");
        // 使用系统提供的默认的恢复策略
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler());
        String xml = null;
        try {
            // 执行getMethod
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: "
                        + getMethod.getStatusLine());
            }
            // 读取内容
            byte[] responseBody = getMethod.getResponseBody();
            // 处理内容
            //System.out.println(new String(responseBody, "UTF-8"));
            xml = new String(responseBody, "UTF-8");
        } catch (Exception e) {
            // 发生致命的异常，可能是协议不对或者返回的内容有问题
            System.out.println("Please check your provided http address!");
            e.printStackTrace();
            logger.error(e.getMessage());
            return xml;
        } finally {
            // 释放连接
            getMethod.releaseConnection();
        }
        return xml;
    }

    /**
     * @Author: 杨青桦
     * @Description: 获取市和区的天气
     * @Date: 2018/1/23 10:36
     * @param xml
     * @param city
     * @return
     */
    public static ChartsCityWeatherView getCityWeather(String xml,String city){
        ChartsCityWeatherView cityWeather = null;
        try {
            Document doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            //得到文档的根节点
            Element root = doc.getRootElement();
            //从根节点中选择出节点名为city的子节点，构成一个节点list
            Iterator iters = root.elementIterator("city");
            //通过循环将每个city节点中的数据解析出来
            while (iters.hasNext()) {
                Element itemEle = (Element) iters.next();
                Attribute cityname = itemEle.attribute("cityname");
                if(city.equals(cityname.getValue())){
                    cityWeather = new ChartsCityWeatherView();
                    Attribute pyName = itemEle.attribute("pyName");
                    Attribute stateDetailed = itemEle.attribute("stateDetailed");
                    Attribute tem1 = itemEle.attribute("tem1");
                    Attribute tem2 = itemEle.attribute("tem2");
                    Attribute windState = itemEle.attribute("windState");
                    cityWeather.setCityname(cityname.getValue());
                    cityWeather.setPyName(pyName.getValue());
                    cityWeather.setStateDetailed(stateDetailed.getValue());
                    cityWeather.setTem1(tem1.getValue());
                    cityWeather.setTem2(tem2.getValue());
                    cityWeather.setWindState(windState.getValue());
                    break;
                }
            }

        } catch (DocumentException e) {
            logger.error("xml解析异常");
            e.printStackTrace();
        }
        return cityWeather;
    }

    /**
     * @Author: 杨青桦
     * @Description: 获取省会和直辖市的天气
     * @Date: 2018/1/23 10:36
     * @param xml
     * @param province
     * @return
     */
    public static ChartsCityWeatherView getProvincialCapitalWeather(String xml,String province){
        ChartsCityWeatherView cityWeather = null;
        try {
            Document doc = DocumentHelper.parseText(xml); // 将字符串转为XML
            //得到文档的根节点
            Element root = doc.getRootElement();
            //从根节点中选择出节点名为city的子节点，构成一个节点list
            Iterator iters = root.elementIterator("city");
            //通过循环将每个city节点中的数据解析出来
            while (iters.hasNext()) {
                Element itemEle = (Element) iters.next();
                Attribute pyName = itemEle.attribute("pyName");
                if(province.equals(pyName.getValue())){
                    cityWeather = new ChartsCityWeatherView();
                    Attribute cityname = itemEle.attribute("cityname");
                    Attribute stateDetailed = itemEle.attribute("stateDetailed");
                    Attribute tem1 = itemEle.attribute("tem1");
                    Attribute tem2 = itemEle.attribute("tem2");
                    Attribute windState = itemEle.attribute("windState");
                    cityWeather.setCityname(cityname.getValue());
                    cityWeather.setPyName(pyName.getValue());
                    cityWeather.setStateDetailed(stateDetailed.getValue());
                    cityWeather.setTem1(tem1.getValue());
                    cityWeather.setTem2(tem2.getValue());
                    cityWeather.setWindState(windState.getValue());
                    break;
                }
            }

        } catch (DocumentException e) {
            logger.error("xml解析异常");
            e.printStackTrace();
        }
        return cityWeather;
    }

    //测试
    public static void main(String[] args) throws Exception{
        String xml = getXml("china");
        System.out.println(getCityWeather(xml,"北京"));
    }

}
